/**
 * 简单的API测试脚本
 * 使用Node.js的http模块直接测试后端API
 * 
 * 使用方法:
 * node api-test.js
 */

const http = require('http');

// 测试API函数
function testAPI(path, method = 'GET', data = null) {
  console.log(`\n测试API: ${method} http://localhost:8080${path}`);
  
  const options = {
    hostname: 'localhost',
    port: 8080,
    path: path,
    method: method,
    headers: {
      'Content-Type': 'application/json',
    }
  };

  return new Promise((resolve, reject) => {
    const req = http.request(options, (res) => {
      console.log(`状态码: ${res.statusCode}`);
      console.log(`响应头: ${JSON.stringify(res.headers)}`);
      
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        console.log('响应数据:', data);
        try {
          const jsonData = JSON.parse(data);
          resolve(jsonData);
        } catch (e) {
          console.log('响应不是有效的JSON:', e.message);
          resolve(data);
        }
      });
    });
    
    req.on('error', (e) => {
      console.error(`请求错误: ${e.message}`);
      reject(e);
    });
    
    if (data) {
      req.write(JSON.stringify(data));
    }
    
    req.end();
  });
}

// 运行测试
async function runTests() {
  try {
    // 测试获取系统信息
    await testAPI('/api/system/owner');
    await testAPI('/api/system/contract-info');
    
    // 测试获取产品列表
    await testAPI('/api/product/list');
    await testAPI('/api/product');
    
    // 测试添加产品
    const productData = {
      id: "TEST001",
      name: "测试产品",
      producer: "测试生产商",
      productionDate: new Date().getTime(),
      origin: "测试产地"
    };
    await testAPI('/api/product', 'POST', productData);
    
    // 再次获取产品列表
    await testAPI('/api/product/list');
    
  } catch (error) {
    console.error('测试失败:', error);
  }
}

// 执行测试
runTests(); 